const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const Device = require('../models/Device');

exports.login = async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ where: { username } });

  if (!user || !bcrypt.compareSync(password, user.password)) {
    return res.status(401).json({ error: '用户名或密码错误' });
  }

  const token = jwt.sign(
    { id: user.id, role: user.role },
    process.env.JWT_SECRET,
    { expiresIn: '1h' }
  );

  res.json({ token, user: { id: user.id, role: user.role } });
};

exports.register = async (req, res) => {
  const { username, password } = req.body;
  const hashedPassword = bcrypt.hashSync(password, 10);

  try {
    const user = await User.create({
      username,
      password: hashedPassword,
      role: 'user'
    });
    res.status(201).json(user);
  } catch (error) {
    res.status(400).json({ error: '注册失败，请检查输入' });
  }
};

exports.getProfile = async (req, res) => {
  try {
    const user = await User.findByPk(req.user.id);
    if (!user) {
      return res.status(404).json({ error: '用户不存在' });
    }

    // 获取用户的设备数量
    const deviceCount = await Device.count({
      where: { userId: req.user.id }
    });

    res.json({
      username: user.username,
      createdAt: user.createdAt,
      deviceCount
    });
  } catch (error) {
    res.status(500).json({ error: '获取用户信息失败' });
  }
};